package com.wtz.temptest.process;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Objects;

/**
 * Date: 2020/11/9
 * Company: www.dtstack.com
 *
 * @author tiezhu
 */
public class TempDemoFive {
    private static final int LISTENER_PORT = 4444;
    private static final String CLASSPATH = "/Users/wtz/IdeaProjects/TempProject/TempTest/target/classes";
    private static final String WORKING_DIRECTORY = "/Users/wtz/IdeaProjects/TempProject/TempTest";

    public static void startJavaProcess() throws Exception {
        final JavaProcessBuilder javaProcessBuilder = new JavaProcessBuilder();
        if ("mac os x".equals(System.getProperty("os.name").toLowerCase())) {
            javaProcessBuilder.setJavaRuntime("java");
        }
        javaProcessBuilder.setWorkingDirectory(WORKING_DIRECTORY);
        javaProcessBuilder.addClassPath(CLASSPATH);
        javaProcessBuilder.setMainClass("com.wtz.temptest.process.HelloWorldServer");
        javaProcessBuilder.addMainClassArguments(String.valueOf(LISTENER_PORT));
        final Process process = javaProcessBuilder.startProcess();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        new Thread(
                () -> {
                    try {
                        Thread.sleep(10000);
                        Socket socket = new Socket("localhost", LISTENER_PORT);
                        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        System.out.println("Client: Sending 'hello' command");
                        out.println("hello");
                        System.out.println("Client: Received '" + in.readLine() + "' from the server");
                        Thread.sleep(20000);
                        System.out.println("Client: Send 'stop' command");
                        out.println("stop");
                        System.out.println("Client Received '" + in.readLine() + "' from the server");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                , "processA").start();
        String line;
        while (Objects.nonNull(line = bufferedReader.readLine())) {
            System.out.println("Server: " + line);
        }
    }

    public static void main(String[] args) throws Exception {
        startJavaProcess();
    }
}
